# coding:utf-8
import json
import os
import logging
import datetime

# 查找重复文件
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
strftime = datetime.datetime.now().strftime('%Y-%m-%d')
if __name__ == '__main__':
    # 用户路径
    user_dir = os.path.expanduser('~') + os.sep
    # print(user_dir)
    # filePath = user_dir + "Videos"
    filePath = user_dir + "Downloads" + os.sep
    # filePath = "D:\视频"
    r = {}
    delete_file = []
    for root, dirs, files in os.walk(filePath):
        for file in files:
            cur_file = os.path.join(root, file)
            filename, file_type = os.path.splitext(file)
            if file_type == '.ts':
                file_list = r.get(filename)
                if file_list is None or len(file_list) == 0:
                    file_list = [cur_file]
                    # r[filename] = file_list
                else:
                    # 存在 判断文件是否相同
                    # 当前文件大小
                    cur_file_size = os.path.getsize(cur_file) / float(1024 * 1024)
                    # for item in file_list:
                    e = enumerate(file_list, 0)
                    for i, item in e:
                        # print(len(item))
                        getsize = os.path.getsize(item) / float(1024 * 1024)
                        if cur_file == item:
                            continue
                        elif cur_file_size == getsize:
                            if len(item) < len(cur_file):
                                file_list[i] = cur_file
                                delete_file.append(item)
                                os.remove(item)
                            else:
                                delete_file.append(cur_file)
                                os.remove(cur_file)
                        else:
                            file_list.append(cur_file)
                r[filename] = file_list

    file_name = '%s-%s.txt' % ('删除文件', strftime)
    with open(file_name, 'w', encoding='utf-8') as f:
        # 循环写入文件
        for item in delete_file:
            f.write(item + '\n')
            # os.remove(item)
    # print(r)
